<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Autonym;
use App\Models\Enter;
use App\Models\Recharge;
use App\Models\Unbind;
use App\Models\User;
use App\Models\Currency;
use App\Models\Property;
use DB;
use Exception;
use Illuminate\Http\Request;

//商家管理
class BusinessController extends Controller
{
    public function __construct()
    {
        view()->share('menu', 'business');
    }

    /**
     * 商家列表
     * @param  Request $request [description]
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function business_list(Request $request)
    {
        //会员ID（账号）
        $account = $request->get('account');
        //条件查询
        $data = User::where(['type' => 2, 'attestation' => 2])
            ->where(function ($query) use ($account) {
                $query->where('account', 'like', '%' . $account . '%');
            })->orderBy('attesta_time', 'desc')->paginate(10);
        //分页索引
        $page_num = $data->firstItem();

        return view('admin/legal/business_list', compact('data', 'account', 'page_num'));
    }

    /**
     * 商家审核列表
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function busi_check_list(Request $request)
    {
        //会员ID
        $account = $request->get('account');
        //类似该ID的所有user的id
        $ids = User::where('account', 'like', '%' . $account . '%')->pluck('id')->toArray();

        /*$data = User::where(['type' => 2, 'attestation' => 1, 'real_status' => 2])
        ->where(function ($query) use ($account) {
        $query->where('account', 'like', '%'.$account.'%');
        })->paginate(10); */

        //条件查询
        $data = Enter::where(function ($query) use ($ids) {
            if (count($ids) > 0) {
                $query->whereIn('uid', $ids);
            }
        })->where('status', '<>', 2)->orderBy('created_at', 'desc')->paginate(8);
        //分页索引
        $page_num = $data->firstItem();

        return view('admin/legal/busi_check_list', compact('data', 'page_num', 'account'));
    }

    /**
     * 审核页面
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function audit_business(Request $request)
    {
        //用户id
        $uid = $request->get('uid');
        //查找用户
        $user = User::find($uid);
        $os = config('alioss.host');

        return view('admin/legal/audit_business', compact('user','os'));
    }

    /**
     * 审核状态修改
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function update_audit_status(Request $request)
    {
        //商家用户id
        $uid = $request->get('uid');
        //状态值
        $status = $request->get('status');
        //备注
        $note = $request->get('note');
        //查找实名认证提交信息
        $autonym = Autonym::where(['uid' => $uid])->first();
        //未找到
        if (count($autonym) == 0) {
            return back()->with(['status' => 0, 'msg' => '没有实名信息']);
        }
        //查找用户
        $user = User::find($uid);
        $enter = Enter::where('uid', $uid)->first();
        try {
            //开启事务
            DB::beginTransaction();
            if ($status == 1) {
                //通过
                $user->update([
                    'type'         => 2,
                    'attestation'  => 2,
                    'attesta_time' => time(),
                ]);
            }else{
                $cid = Currency::where('name_en', 'OBA')->value('id');
                $property = Property::where(['uid' => $uid, 'cid' => $cid])->first();
                $property->increment('balance', 30000);
                $property->decrement('blocked', 30000);
            }
            $enter->update([
                'status' => $status,
                'note'   => $note,
            ]);
            DB::commit();
            Unbind::where('uid',$uid)->delete();
            return redirect('/admin/busi_check_list');
        } catch (Exception $e) {
            DB::rollback();
            //$msg = $e->getMessage();//接收错误号
            return respF(4013);
        }
    }

    /**
     * 解绑申请列表
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function unbind_list(Request $request)
    {
        //会员ID
        $account = $request->get('account');
        //条件查询
        $data = Unbind::where(function ($query) use ($account) {
            if (!empty($account)) {
                //根据账号查找商家id
                $ids = User::where(['type' => 2, 'attestation' => 2])
                    ->where('account', 'like', '%' . $account . '%')
                    ->pluck('id');
                $query->whereIn('uid', $ids);
            }
        })->orderBy('created_at', 'desc')->paginate(8);

        $page_num = $data->firstItem();

        return view('admin/legal/unbind_list', compact('data', 'account', 'page_num'));
    }

    /**
     * 注销商家
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function unbind_business(Request $request)
    {
        try {
            //验证参数
            if (!$request->has('uid')) {
                throw new Exception('uid参数必须');
            }
            //商家用户id
            $uid = $request->get('uid');
            //查找用户
            $user = User::find($uid);
            //未找到用户
            if (!$user) {
                //抛出错误
                throw new Exception('商家不存在');
            }
            //查询是否有未完成的订单
            $orders = Recharge::where(['bid' => $uid])->whereIn('status', [2, 5])->get();
            if (count($orders) > 0) {
                throw new Exception('有未完成订单，不能注销');
            }

            //查找解绑申请表
            $unbind = Unbind::where('uid', $uid)->first();
            //开启事务
            DB::beginTransaction();
            //修改解绑状态
            $unbind->update([
                'status' => 2,
            ]);
            //修改用户身份
            $user->update([
                'type' => 1,
            ]);
            //USDT的币种id
            //$cid = Currency::where('name_en', 'USDT')->value('id');
            //获取用户USDT资产
            //$userProperty = $user->currency_property($cid)->first();
            //获取入驻冻结资产
            //$enter = Enter::where('uid', $uid)->first();
            //入驻冻结的资产是否作为抵押不能动用？？？？？如果资产不足，怎么解绑？？？
            //if ($enter->usdt_num > $userProperty->blocked) {
            //throw new Exception('冻结资产不足，解绑失败');
            //}

            //解冻入驻冻结的usdt资产
            //$userProperty->decrement('blocked', $enter->usdt_num);
            //增加可用资产
            //$userProperty->increment('balance', $enter->usdt_num);

            //提交事务
            DB::commit();

            return back()->with(['status' => 1, 'msg' => '操作成功']);

        } catch (Exception $e) {
            //回滚事务
            DB::rollback();
            //接收错误提示
            $msg = $e->getMessage();

            return back()->with(['status' => 0, 'msg' => $msg]);
        }
    }
}
